import pandas as pd
import numpy as np
import os
from typing import List
def to_matrix_from_tab(fp_tab: str) -> List[List[str]]:
    with open(fp_tab, mode='r') as f:
        lines = f.read().splitlines()
        n = len(lines)
        # calc i0
        i0 = -1
        for i in range(0, n):
            if lines[i].startswith('TAGTAG'):
                i0 = i
                break
        i0 += 1
        if i0 >= n-1:
            return pd.DataFrame()
        cols =['code','market','name','position']
        body = []
        for i in range(i0, n-1):
            body.append(lines[i].split('|'))

        return pd.DataFrame(body, columns=cols)

codeModifiedS5=pd.DataFrame()
#codeModifiedS5=to_matrix_from_tab('C002_buy_314_5.ini')
#codeModifiedS5['position']=codeModifiedS5['position'].astype('float64')
#codeModifiedS5['position']=2*codeModifiedS5['position']

codeModifiedSD=pd.DataFrame()
#codeModifiedSD=to_matrix_from_tab('C002_buy_314_D.ini')
#codeModifiedSD['position']=codeModifiedSD['position'].astype('float64')
#codeModifiedSD['position']=1*codeModifiedSD['position']

ratio=0.25

#from WindPy import w
#w.start()

#data=pd.read_excel('综合信息查询_组合证券_S5_20200219.xls')
data=pd.read_excel('综合信息查询_组合证券SD20200310.xls')
position=list(data['持仓'])
buypos=list(data['当日买量'])
stocks=list(data['证券代码'])
names=list(data['证券名称'])
mv=list(data['市值'])
price=list(data['最新价'])
account=list(data['组合编号'])
codeList=[]
for i in range(len(stocks)):
    if np.isnan(stocks[i]):
        continue
        
    code=int(stocks[i])
    pos=position[i]
    #pos=position[i]-buypos[i]
    #pos=np.floor(pos*1/100)*100
    codeStr=str(code).rjust(6,'0')
    acc=int(account[i])
    if ((codeStr<'009999')|((codeStr>='300000') & (codeStr<='309999'))):
        codeStr+='.SZ'
    elif ((codeStr>='600000') & (codeStr<='609999')):
        codeStr+='.SH'
    else:
        continue
    codeList.append({'code':codeStr,'account':acc,'hold':pos,'name':names[i],'marketValue':mv[i],'price':price[i]})
allStocks=pd.DataFrame(codeList)

myStocks=allStocks[allStocks['account']==30014005]
print(30014005)
#deleteCodes=["000001.SZ","600036.SH","601166.SH","600000.SH","601818.SH","600016.SH","601998.SH","600015.SH"]
#myStocks=myStocks[~myStocks['code'].isin(deleteCodes)]
if myStocks.shape[0]>0:
    codes=list(myStocks['code'])
    stocks=myStocks[['code','hold','price']]
    if (codeModifiedS5.shape[0]>0):
        codeModified=codeModifiedS5
        result=[]
        for index, row in stocks.iterrows():
            code=row['code']
            hold=row['hold']
            price=row['price']
            codenum=code.split('.')[0]
            canuse=hold
            if (codeModified[codeModified['code']==codenum].shape[0]>=1):
                canuse=hold-codeModified[codeModified['code']==codenum]['position'].iloc[0]
            result.append({'code':code,'hold':canuse,'price':price})
        stocks=pd.DataFrame(result)
    stocks['hold']=stocks['hold'].apply(lambda x:np.floor(x*ratio/100)*100)
    stocks['parameter1']=0.004
    stocks['parameter2']=0.4
    mv=(stocks['hold']*stocks['price']).sum()
    print(mv)
    stocks['hold']=stocks['hold']
    stocks=stocks[stocks['hold']>=200]
    stocks=stocks[stocks['price']>=5]
    mv=(stocks['hold']*stocks['price']).sum()
    print(mv)
    stocks=stocks[['code','hold','parameter1','parameter2']]
    stocks.to_csv("stock5.csv",index=0,header=0)
    control=stocks[['code','hold']]
    control.to_csv("control5.csv",index=0,header=0)
print("+++++++++++++++++++++++++++++++++++++++++")

myStocks=allStocks[allStocks['account']==314]
print(314)
if myStocks.shape[0]>0:
    codes=list(myStocks['code'])
    stocks=myStocks[['code','hold','price']]
    if (codeModifiedSD.shape[0]>0):
        codeModified=codeModifiedSD
        result=[]
        for index, row in stocks.iterrows():
            code=row['code']
            hold=row['hold']
            price=row['price']
            codenum=code.split('.')[0]
            canuse=hold
            if (codeModified[codeModified['code']==codenum].shape[0]>=1):
                canuse=hold-codeModified[codeModified['code']==codenum]['position'].iloc[0]
            result.append({'code':code,'hold':canuse,'price':price})
        stocks=pd.DataFrame(result)
    stocks['hold']=stocks['hold'].apply(lambda x:np.floor(x*ratio/100)*100)
    stocks['parameter1']=0.0035
    stocks['parameter2']=0.4
    mv=(stocks['hold']*stocks['price']).sum()
    print(mv)
    stocks['hold']=stocks['hold']
    stocks=stocks[stocks['hold']>=200]
    stocks=stocks[stocks['price']>=5]
    mv=(stocks['hold']*stocks['price']).sum()
    print(mv)
    stocks=stocks[['code','hold','parameter1','parameter2']]
    stocks.to_csv("stockD.csv",index=0,header=0)
    control=stocks[['code','hold']]
    control.to_csv("controlD.csv",index=0,header=0)





